package com.xbts.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.xbts.common.config.XbtsConfig;
import com.xbts.common.core.domain.model.LoginUser;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.SecurityUtils;
import com.xbts.common.utils.ServletUtils;
import com.xbts.common.utils.StringUtils;
import com.xbts.common.utils.file.FileUploadUtils;
import com.xbts.system.domain.SeiMaterial;
import com.xbts.system.domain.SeiMaterialTemplate;
import com.xbts.system.domain.SeiTemplate;
import com.xbts.system.domain.Templates;
import com.xbts.system.domain.dto.InsertMaterialToTemplateDto;
import com.xbts.system.domain.enums.StyleEnum;
import com.xbts.system.domain.utils.FileUtil;
import com.xbts.system.domain.utils.HtmlUtil;
import com.xbts.system.mapper.SeiTemplateMapper;
import com.xbts.system.service.ISeiMaterialService;
import com.xbts.system.service.ISeiMaterialTemplateService;
import com.xbts.system.service.ISeiTemplateService;
import fr.opensagres.poi.xwpf.converter.core.FileImageExtractor;
import fr.opensagres.poi.xwpf.converter.core.FileURIResolver;
import fr.opensagres.poi.xwpf.converter.core.XWPFConverterException;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.ddr.poi.html.HtmlRenderPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * 基本信息表Service业务层处理
 *
 * @author xbts
 * @date 2023-08-21
 */
@Slf4j
@Service
public class SeiTemplateServiceImpl extends ServiceImpl<SeiTemplateMapper, SeiTemplate> implements ISeiTemplateService {


    @Autowired
    private SeiTemplateMapper seiTemplateMapper;
    @Autowired
    private ISeiMaterialService materialService;
    @Autowired
    private ISeiMaterialTemplateService materialTemplateService;

    /**
     * 查询模板
     *
     * @return 模板列表
     */
    @Override
    public List<SeiTemplate> selectTemplateList(SeiTemplate seiTemplate) {
        return seiTemplateMapper.selectTemplateList(seiTemplate.queryWrapper());
    }

    /**
     * 修改模板
     *
     * @param seiTemplate 模板
     * @return 结果
     */
    @Override
    public boolean updateTemplate(SeiTemplate seiTemplate) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("用户未登录");
        }
        if (!seiTemplate.getCreateBy().equals(SecurityUtils.getUserId().toString())) {
            throw new ServiceException("没有权限修改");
        }
        return updateById(seiTemplate);
    }

    /**
     * 新增模板类型
     *
     * @param name 模板标题
     * @return 结果
     */
    @Override
    public boolean insertTemplateType(String name) {
        if (name == null) {
            throw new ServiceException("名称不能为空");
        }
        SeiTemplate seiTemplate = new SeiTemplate();
        seiTemplate.setCreateBy(SecurityUtils.getUserId().toString());
        QueryWrapper<SeiTemplate> queryWrapper = new QueryWrapper<>();
        if (getOne(queryWrapper.eq("name", name)) != null) {
            throw new ServiceException("重复模板类型名称");
        }
        seiTemplate.setParentId("0");
        seiTemplate.setName(name);
        return save(seiTemplate);
    }

    /**
     * 新增模板
     *
     * @param seiTemplate 模板
     * @return 结果
     */
    @Override
    public boolean insertTemplate(SeiTemplate seiTemplate) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("用户未登录");
        }
        seiTemplate.setCreateBy(SecurityUtils.getUserId().toString());
        seiTemplate.setAffiliationName(loginUser.getUser().getNickName());
        return save(seiTemplate);
    }

    /**
     * 删除模板
     *
     * @param templateId 模板Id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTemplate(String templateId) {
        String userType = SecurityUtils.getLoginUser().getUser().getUserType();
        if("02".equals(userType)){
            SeiTemplate seiTemplate = this.getById(templateId);
            if(!seiTemplate.getCreateBy().equals(SecurityUtils.getUserId().toString())){
                throw new ServiceException("只能删除自己的模板！");
            }
        }
        return removeById(templateId);
    }

    /**
     * 批量删除模板
     *
     * @param ids 模板Id集合
     * @return 结果
     */
    @Override
    public boolean batchDeleteTemplate(List<String> ids) {
        String userType = SecurityUtils.getLoginUser().getUser().getUserType();
        if("02".equals(userType)){
            for (String id : ids) {
                SeiTemplate seiTemplate = this.getById(id);
                if(!seiTemplate.getCreateBy().equals(SecurityUtils.getUserId().toString())){
                    throw new ServiceException("只能删除自己的模板！");
                }
            }
        }
        removeBatchByIds(ids);
        return true;
    }

    /**
     * 查询模板详情
     *
     * @param templateId 模板主键
     * @return 模板
     */
    @Override
    public SeiTemplate selectSeiByTemplateId(String templateId) {

        SeiTemplate template = getById(templateId);

        // 查询所有素材
        List<SeiMaterial> list = materialService.list();

        if (list.size() < 1) {
            return template;
        }
        Map<String, SeiMaterial> seiMaterialMap = list.stream().collect(Collectors.toMap(SeiMaterial::getMaterialId, v -> v));

        List<SeiMaterialTemplate> seiMaterialTemplates = materialTemplateService.list(new LambdaQueryWrapper<SeiMaterialTemplate>()
                .eq(SeiMaterialTemplate::getTemplateId, templateId)
                .eq(SeiMaterialTemplate::getType, 1));
        if (seiMaterialTemplates.size() > 0) {
            for (SeiMaterialTemplate seiMaterialTemplate : seiMaterialTemplates) {
                SeiMaterial material = seiMaterialMap.get(seiMaterialTemplate.getSecondLevelMaterialId());
                if (StringUtils.isNull(material)) {
                    continue;
                }
                material.setSelectedMaterialId(seiMaterialTemplate.getThreeLevelMaterialId());
                SeiMaterial seiMaterial = seiMaterialMap.get(seiMaterialTemplate.getThreeLevelMaterialId());
                if(StringUtils.isNotNull(seiMaterial)) {
                    material.setSelectedMaterialName(seiMaterial.getName());
                }
            }
        }
        List<SeiMaterial> materialTree = new ArrayList<>();
        for (SeiMaterial seiMaterial : list) {
            if (seiMaterial.getType() == 3) continue;

            String parentId = seiMaterial.getParentId();
            if (StringUtils.isBlank(parentId) || "0".equals(parentId)) {
                materialTree.add(seiMaterial);
                continue;
            }
            SeiMaterial material = seiMaterialMap.get(seiMaterial.getParentId());
            if (StringUtils.isNotNull(material)) {
                material.getChildren().add(seiMaterial);
            }
        }
        template.setMaterialTree(materialTree);

        List<SeiMaterialTemplate> materialTemplates = materialTemplateService.list(new LambdaQueryWrapper<SeiMaterialTemplate>()
                .eq(SeiMaterialTemplate::getTemplateId, templateId));

        for (SeiMaterialTemplate materialTemplate : materialTemplates) {
            String threeLevelMaterialId = materialTemplate.getThreeLevelMaterialId();
            SeiMaterial material = materialService.getById(threeLevelMaterialId);
            if(StringUtils.isNotNull(material)){
                materialTemplate.setContent(material.getContent());
                materialTemplate.setThreeLevelMaterialName(material.getName());
            }
        }
        InsertMaterialToTemplateDto insertMaterialToTemplateDto = new InsertMaterialToTemplateDto();
        insertMaterialToTemplateDto.setTemplateId(templateId);
        insertMaterialToTemplateDto.setList(materialTemplates);
        template.setMaterialToTemplateDto(insertMaterialToTemplateDto);

        return template;
    }

    /**
     * 导出word文档
     *
     * @param template,response 回应头，模板
     */
    @Override
    public void outPutWord(HttpServletRequest request, HttpServletResponse response, String template) {

        // 使用正则表达式来截取图片路径
        Pattern imgSrcPattern = Pattern.compile("<img src=\"(.*?)\"");
        Matcher matcher = imgSrcPattern.matcher(template);

        // 循环遍历所有找到的图片路径
        while (matcher.find()) {
            String oldImagePath = matcher.group(1);  // 获取原始图片路径
            if(oldImagePath.indexOf("data:image") >= 0){
                continue;
            }
            String profile = XbtsConfig.getProfile();
            String tempImagePath = oldImagePath.replaceAll(".*?/profile", profile);
            log.info("tempImagePath=-------------------:" + tempImagePath);

            // 转为base64
            try {
                String baseString = base64String(tempImagePath);
                String newImagePath = "data:image/jpeg;base64," + baseString;

                // 创建一个新的富文本字符串，用新的图片路径替换旧路径
                template = template.replaceAll(oldImagePath, newImagePath);
            }catch (IOException e){
                log.error("图片转base64失败。图片地址->" + oldImagePath);
            }
        }
//        System.out.println("图片转base64后->" +template);  // 输出修改后的富文本字符串

        //2、指定数据
        Map<String, Object> data = new HashMap(8);
        String[] split = template.split("<div class=\"page-break\" style=\"page-break-after:always;\"><span style=\"display:none;\">&nbsp;</span></div>");
        ConfigureBuilder builder = Configure.builder();
        Configure config = builder.build();

        saveTemplates(split.length);
        for (int i = 0; i < split.length; i++) {
            template = split[i];
            //1、数据来源,实际项目里是通过sql查询出来的
            Templates templates = new Templates();

            templates.setRichTextOne(template);

            HtmlRenderPolicy htmlRenderPolicy = new HtmlRenderPolicy();
            data.put("basicInfoOne", templates.getBasicInfoOne());

            //4.2、处理后图片样式
            data.put("r" + i, dealWithPictureWidthAndHeight(templates.getRichTextOne()));
            //4.2.1、指定插件
            config.customPolicy("r" + i, htmlRenderPolicy);
        }

        //临时路径，实际项目里不需要
        String filePath = FileUtil.getProjectPath() + "document" + File.separator + "牧羊人导出实例.docx";
        //动态导出
        try {
//            dynamicExportWord(data, new File(filePath), new ClassPathResource("templates" + File.separator + "导出模板.docx"), config, response, true);
            dynamicExportWord(data, new File(filePath), new PathResource(FileUtil.getProjectPath() + "template.docx"), config, response, true);

        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }

    }
    public static void saveTemplates(int size) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("templates" + File.separator + "导出模板.docx");
            InputStream inputStream = classPathResource.getInputStream();
//            FileInputStream fis = new FileInputStream();
            XWPFDocument document = new XWPFDocument(inputStream);
            inputStream.close();

            for (int i = 0; i < size; i++) {
                // 创建另一个段落，这将在新页面上显示
                XWPFParagraph contentParagraph = document.createParagraph();
                XWPFRun run = contentParagraph.createRun();
                run.setText("{{r" + i + "}}");
                if(i < size - 1) {
                    // 创建一个新段落，将其设置为分页段落
                    XWPFParagraph pageBreakParagraph = document.createParagraph();
                    pageBreakParagraph.setPageBreak(true);
                }
            }
            File wordFile = new File(FileUtil.getProjectPath() + "template.docx");
            if (!wordFile.exists()) {
                createNewWordFile(wordFile);
            }
            // 保存文档
            FileOutputStream fos = new FileOutputStream(FileUtil.getProjectPath() + "template.docx");
            document.write(fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void createNewWordFile(File wordFile) {
        try {
//            wordFile.delete();
            XWPFDocument document = new XWPFDocument();

            // 在新文档中添加内容
            // ...

            // 保存新文档
            FileOutputStream fos = new FileOutputStream(wordFile);
            document.write(fos);
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Transactional
    @Override
    public boolean insertMaterialToTemplate(InsertMaterialToTemplateDto dto) {

        materialTemplateService.remove(new LambdaQueryWrapper<SeiMaterialTemplate>()
                .eq(SeiMaterialTemplate::getTemplateId, dto.getTemplateId()));

        List<SeiMaterialTemplate> list = dto.getList();

        if (StringUtils.isNull(list) || list.size() < 1) {
            return true;
        }
        Map<String, SeiMaterial> map = materialService.list(new LambdaQueryWrapper<SeiMaterial>()
                        .in(SeiMaterial::getMaterialId, list.stream().map(SeiMaterialTemplate::getThreeLevelMaterialId).collect(Collectors.toList())))
                .stream().collect(Collectors.toMap(SeiMaterial::getMaterialId, v -> v));

        for (SeiMaterialTemplate materialTemplate : list) {
            SeiMaterial seiMaterial = map.get(materialTemplate.getThreeLevelMaterialId());
            if (StringUtils.isNotNull(seiMaterial)) {
                materialTemplate.setSecondLevelMaterialId(seiMaterial.getParentId());
            }
            materialTemplate.setTemplateId(dto.getTemplateId());
        }
        // 保存素材与模板的关联
        return materialTemplateService.saveBatch(list);
    }

    @Override
    public int insertNewTemplate(InsertMaterialToTemplateDto dto) {
        SeiTemplate template = new SeiTemplate();
        template.setName(dto.getName());
        template.setTemplateTypeId(dto.getTemplateTypeId());
        template.setCreateBy(SecurityUtils.getUserId().toString());
        template.setTemplateTypeId(dto.getTemplateTypeId());
        this.save(template);
        dto.setTemplateId(template.getTemplateId());
        this.insertMaterialToTemplate(dto);
        return 1;
    }

    @Override
    public String importData(MultipartFile file) {
        Templates templates = new Templates();
        //3、下载文件到临时路径下
        File destFile = FileUtil.fileDownloadToLocalPath(file);
        //4、处理富文本信息(含图片),并且定义一个实体类接收
        dealWithTemplatesRichText(templates, destFile);
        //5、替换案例富文本信息中的图片(如果有)路径并删除临时文件和临时图片
        try {
            dealWithTemplatesRichTextToPicture(templates);
        } catch (NotOfficeXmlFileException e) {
            throw new ServiceException("文件格式异常，请使用正常的docx文件！");
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
        return templates.getRichTextOne();
    }

    private String dealWithPictureWidthAndHeight(String content) {
        List<HashMap<String, String>> imagesFiles = HtmlUtil.regexMatchWidthAndHeight(content);
        if (imagesFiles.size() > 0) {
            for (HashMap<String, String> imagesFile : imagesFiles) {
                String newFileUrl = imagesFile.get(StyleEnum.NEW_FILE_URL.getValue());
                String fileUrl = imagesFile.get(StyleEnum.FILE_URL.getValue());
                if (newFileUrl != null) {
                    content = content.replace(fileUrl, newFileUrl);
                }
            }
        }
        return content;
    }

    public String base64String(String filePath) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        FileInputStream fileInputStream = new FileInputStream(filePath);
        byte[] bytes = new byte[1024];
        //用来定义一个准备接收图片总长度的局部变量
        int len;
        //将流的内容读取到bytes中
        while ((len = fileInputStream.read(bytes)) > 0) {
            //将bytes内存中的内容从0开始到总长度输出出去
            out.write(bytes, 0, len);
        }
        //通过util包中的Base64类对字节数组进行base64编码
        return Base64.getEncoder().encodeToString(out.toByteArray());
    }

    public String is2Base64String(InputStream fileInputStream) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
//        FileInputStream fileInputStream = new FileInputStream(filePath);
        byte[] bytes = new byte[1024];
        //用来定义一个准备接收图片总长度的局部变量
        int len;
        //将流的内容读取到bytes中
        while ((len = fileInputStream.read(bytes)) > 0) {
            //将bytes内存中的内容从0开始到总长度输出出去
            out.write(bytes, 0, len);
        }
        //通过util包中的Base64类对字节数组进行base64编码
        return Base64.getEncoder().encodeToString(out.toByteArray());
    }

    /**
     * @param data      填充数据
     * @param filePath  临时路径
     * @param resource  模板路径
     * @param response  通过浏览器下载需要
     * @param isBrowser true-通过浏览器下载  false-下载到临时路径
     */
    public void dynamicExportWord(Map<String, Object> data, File filePath, Resource resource, Configure config, HttpServletResponse response, boolean isBrowser) throws IOException {
        // 调整压缩比率限制（以更高的比率为例）
        ZipSecureFile.setMinInflateRatio(0.00001);
        XWPFTemplate render = XWPFTemplate.compile(resource.getInputStream(), config).render(data);
        if (Boolean.FALSE.equals(isBrowser)) {
            File parentFile = filePath.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(filePath);
            render.writeAndClose(out);
        } else {
            File parentFile = filePath.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(filePath);
            render.writeAndClose(out);

            try {
                FileInputStream fis = new FileInputStream(filePath);
                XWPFDocument document = new XWPFDocument(fis);
                fis.close();

                setGlobalFontToSimSun(document);

//                removeTrailingBlankPages(document);
//                removeTrailingBlankParagraphsAndPages(document);

//                FileOutputStream fos = new FileOutputStream("your_output.docx");

                response.setContentType("application/msword");//导出word格式
                response.addHeader("Content-Disposition", "attachment;filename=" + "导出文档.doc");
                response.addHeader("Content-Type", "application/json;charset=UTF-8");
                ServletOutputStream out2 = response.getOutputStream();
                document.write(out2);

//                fos.close();


//            ServletOutputStream out = response.getOutputStream();
//            render.writeAndClose(out);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void setGlobalFontToSimSun(XWPFDocument document) {
        // 遍历文档的段落
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            // 遍历段落中的文本运行
            for (XWPFRun run : paragraph.getRuns()) {
                // 设置字体为宋体
                run.setFontFamily("SimSun");
            }
        }

        // 遍历文档中的表格
        List<XWPFTable> tables = document.getTables();
        for (XWPFTable table : tables) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    // 遍历单元格中的段落
                    for (XWPFParagraph paragraph : cell.getParagraphs()) {
                        // 遍历段落中的文本运行
                        for (XWPFRun run : paragraph.getRuns()) {
                            // 设置字体为宋体
                            run.setFontFamily("SimSun");
                        }
                    }
                }
            }
        }
    }

    public static void removeTrailingBlankPages(XWPFDocument document) {
        int numParagraphs = document.getParagraphs().size();

        // Iterate from the last paragraph to find the last non-empty paragraph
        for (int i = numParagraphs - 1; i >= 0; i--) {
            XWPFParagraph paragraph = document.getParagraphs().get(i);
            if (!isEmptyParagraph(paragraph)) {
                break; // Found the last non-empty paragraph
            } else {
                // Remove empty paragraphs
                document.removeBodyElement(i);
            }
        }
    }

    public static void removeTrailingBlankParagraphsAndPages(XWPFDocument document) {
        int numParagraphs = document.getParagraphs().size();

        boolean foundNonBlankParagraph = false;

        for (int i = numParagraphs - 1; i >= 0; i--) {
            XWPFParagraph paragraph = document.getParagraphs().get(i);

            if (!foundNonBlankParagraph) {
                // 如果未找到非空白段落，继续向前遍历
                if (!isEmptyParagraph(paragraph)) {
                    foundNonBlankParagraph = true;
                }
            } else {
                // 如果已找到非空白段落，删除空白段落
                if (isEmptyParagraph(paragraph)) {
                    document.removeBodyElement(i);
                } else {
                    // 找到非空白段落后停止遍历
                    break;
                }
            }
        }
    }

    public static boolean isEmptyParagraph(XWPFParagraph paragraph) {
        // Use XMLCursor to check if the paragraph is empty
        XmlCursor cursor = paragraph.getCTP().newCursor();
        cursor.selectPath("./*");
        return !cursor.toFirstChild();
//        return StringUtils.isBlank(paragraph.getText());
    }

    private void dealWithTemplatesRichTextToPicture(Templates templates) throws IOException {
        //保存临时图片路径，统一删除
        Set<File> files = new HashSet<>();
        String richTextOne = templates.getRichTextOne();
        String richTextTwo = templates.getRichTextTwo();
        String richTextThree = templates.getRichTextThree();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(richTextOne)) {
            //参数分别是实体类、minio（其他）方法、临时图片路径集合
            String content = dealWithTemplatesRichTextToPictureChild(richTextOne, "ossBuilder", files);
            templates.setRichTextOne(content);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(richTextTwo)) {
            String content = dealWithTemplatesRichTextToPictureChild(richTextTwo, "ossBuilder", files);
            templates.setRichTextTwo(content);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(richTextThree)) {
            String content = dealWithTemplatesRichTextToPictureChild(richTextThree, "ossBuilder", files);
            templates.setRichTextThree(content);
        }
        if (files.size() > 0) {
            for (File file : files) {
                //自行删除
                file.delete();
            }
        }
    }

    private String dealWithTemplatesRichTextToPictureChild(String content, String ossBuilder, Set<File> files) throws IOException {
        //1、正则匹配src
        List<String> imagesFiles = HtmlUtil.regexMatchPicture(content);
        //2、判空
        if (imagesFiles.size() > 0) {
            for (String imagesFile : imagesFiles) {
                File file = new File(imagesFile);
                MultipartFile fileItem = FileUtil.createFileItem(file, file.getName());
                boolean aBoolean = true;
                while (Boolean.TRUE.equals(aBoolean)) {
//                    // 上传文件路径
                    String filePath = XbtsConfig.getUploadPath();
//                    // 上传并返回新文件名称
                    String fileName = FileUploadUtils.upload(filePath, fileItem);
//                    String url = getDomain() + fileName;
//                    String url = XbtsConfig.getLocalIp() + fileName;
                    String ip = XbtsConfig.getLocalIp();
                    if(StringUtils.isBlank(ip)) {
//                        ip = "http://172.17.164.55:8556";
                        ip = "http://192.168.2.148:8556";
                    }
                    String url = ip + fileName;


//                    String baseString = base64String(tempImagePath);
//                    String baseString = is2Base64String(fileItem.getInputStream());
//                    String newImagePath = "data:image/jpeg;base64," + baseString;
                    //这里是调用上传接口返回一个url，然后替换即可
                    content = content.replace(imagesFile, url);
                    //删除临时图片(统一删除 如上传同一张图片，第二次会找不到图片)
                    files.add(file);
                    aBoolean = false;
                }
            }
        }
        return content;
    }

    public String getDomain()
    {
        HttpServletRequest request = ServletUtils.getRequest();
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

    private void dealWithTemplatesRichText(Templates templates, File destFile) {
        if (!destFile.exists()) {
            //导入模板失败,请重新上传！
        } else {
            //1、判断是否为docx文件
            if (destFile.getName().endsWith(".docx") || destFile.getName().endsWith(".DOCX")) {
                // 1)加载word文档生成XWPFDocument对象
                try (FileInputStream in = new FileInputStream(destFile); XWPFDocument document = new XWPFDocument(in)) {
                    // 2)解析XHTML配置（这里设置IURIResolver来设置图片存放的目录）
                    File imageFolderFile = new File(String.valueOf(destFile.getParentFile()));
                    XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));
                    options.setExtractor(new FileImageExtractor(imageFolderFile));
                    options.setIgnoreStylesIfUnused(false);
                    options.setFragment(true);
                    //2、使用字符数组流获取解析的内容
                    ByteArrayOutputStream bass = new ByteArrayOutputStream();
                    XHTMLConverter.getInstance().convert(document, bass, options);
                    String richTextContent = bass.toString();

                    richTextContent = removeOuterStyledDiv(richTextContent);
                    //自定义用于截取的波浪线（可以用其他代替，只要你能够区分）
                    String[] tableSplit = richTextContent.split("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~</span></p>");
                    templates.setRichTextOne(tableSplit[0]);
                } catch (IOException | XWPFConverterException e) {
                    e.printStackTrace();
                } finally {
                    //处理完就删除文件
                    if(destFile.delete()){
                        System.out.println("删除成功");
                    }else{
                        System.out.println("删除失败");
                    }
                }
            }
        }
    }

    public static String removeOuterStyledDiv(String html) {
        // 定义正则表达式来匹配带样式的 div 标签
        String pattern = "<div\\s+style=\"[^>]+\">(.+?)</div>";

        Pattern divPattern = Pattern.compile(pattern);
        Matcher matcher = divPattern.matcher(html);

        if (matcher.find()) {
            // 获取匹配的内容，即带样式的 div 标签
            String matchedDiv = matcher.group();

            // 从原始 HTML 中删除带样式的 div 标签
            String cleanedHtml = html.replace(matchedDiv, matcher.group(1));

            return cleanedHtml;
        } else {
            return html; // 如果没有匹配的带样式的 div 标签，返回原始 HTML
        }
    }

}
